package com.itheima.controller;

import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private HttpServletResponse response;

    @Value("${imgURL.name}")
    private String url;

    @PostMapping("/upload.do")
    public Result upload(MultipartFile imgFile) throws IOException {
        //重新命名
        String newFileName = UUID.randomUUID().toString();
        //获取图片的后缀名
        String oldFileName = imgFile.getOriginalFilename();
        String hzName = oldFileName.substring(oldFileName.lastIndexOf("."));
        newFileName = newFileName + hzName;
        //图片储存到服务器
        imgFile.transferTo(new File(url + newFileName));
        return new Result(true, "图片上传成功", newFileName);
    }

    @PostMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult result = setmealService.findPage(queryPageBean);
        return result;
    }

    @PostMapping("/add.do")
    public Result add(Integer[] checkgroupIds, @RequestBody Setmeal setmeal) {
        Result result = setmealService.add(checkgroupIds, setmeal);
        return result;
    }

    @GetMapping("/findById.do")
    public Result findById(Integer id) {
        Result result = setmealService.findById(id);
        return result;
    }

    @PutMapping("/edit.do")
    public Result update(Integer[] checkgroupIds, @RequestBody Setmeal setmeal) {
        Result result = setmealService.update(checkgroupIds, setmeal);
        return result;
    }

    @DeleteMapping("/{id}")
    public Result remove(@PathVariable Integer id) {
        setmealService.remove(id);
        return new Result(true, "删除成功");

    }
}
